{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "f56a1264",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.a3f4592772d952cc32ab2a3dbee6a32d.315360000.1964436455.282335-25904789', 'expires_in': 2592000, 'session_key': '9mzdWujtQRB9w85gRhfLN+DG/PpU0n9rCLU919tcq3OWSl8/Eu13tAZlSlQBZBdluaPu7Po5pY6SAfRy8oi8sEbyx5sCRw==', 'access_token': '24.a407b16b3489d43c11369208bc1a6b29.2592000.1651668455.282335-25904789', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': 'c14206800f2625f9ebef35abd854ab59'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'wRDgGwTX5TTTS2S1EagbKox1',\n",
    "    'client_secret':'CbOTGqSI6KdwtLtpnzpyVd3buCft4IsZ'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6a7e92fc",
   "metadata": {},
   "source": [
    "## 百度图像识别API调用方式\n",
    "> https://cloud.baidu.com/doc/IMAGERECOGNITION/s/7k3bcxdn8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "4f1cc745",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.a24fa1e55c23b4267cf2d5e7bab27341.315360000.1964436458.282335-25904789', 'expires_in': 2592000, 'session_key': '9mzdXUTBHCj/gfU3NAn7fwcmvlUkkJchOEcGg3SLUlJqtezKs80V+mRbmy7GKIfmwnM72cW0PEc7lDHVz/H1zc1Mope83Q==', 'access_token': '24.f00cdb6a6520c587ffe08914bd0e467a.2592000.1651668458.282335-25904789', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': 'cbc11de2aaeb23522ac49ca94ad1d8e5'}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=wRDgGwTX5TTTS2S1EagbKox1&client_secret=CbOTGqSI6KdwtLtpnzpyVd3buCft4IsZ'\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "ef6c4caa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.f00cdb6a6520c587ffe08914bd0e467a.2592000.1651668458.282335-25904789'"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "access_token = response.json()['access_token']\n",
    "access_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "57d93c0c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "227be9d8",
   "metadata": {},
   "source": [
    "## 通用物体的识别\n",
    "* 接口描述：\n",
    "> 该请求用于通用物体及场景识别，即对于输入的一张图片（可正常解码，且长宽比适宜），输出图片中的多个物体及场景标签。\n",
    "* 请求URL：\n",
    "> https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\n",
    "* 请求参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "66761a74",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>参数</th>\n",
       "      <th>是否必选</th>\n",
       "      <th>类型</th>\n",
       "      <th>可选值范围</th>\n",
       "      <th>说明</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>image</td>\n",
       "      <td>和url二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>url</td>\n",
       "      <td>和image二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>baike_num</td>\n",
       "      <td>否</td>\n",
       "      <td>integer</td>\n",
       "      <td>-</td>\n",
       "      <td>返回百科信息的结果数，默认不返回</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          参数       是否必选       类型 可选值范围  \\\n",
       "0      image    和url二选一   string     -   \n",
       "1        url  和image二选一   string     -   \n",
       "2  baike_num          否  integer     -   \n",
       "\n",
       "                                                  说明  \n",
       "0  图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...  \n",
       "1  图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...  \n",
       "2                                   返回百科信息的结果数，默认不返回  "
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 读取页面表格数据\n",
    "pd.read_html('https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21')[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "2a90483c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '刘德华', 'score': 0.823002, 'root': '公众人物', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%88%98%E5%BE%B7%E5%8D%8E/114923', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/024f78f0f736afc379318042e653fcc4b74543a9b4c8', 'description': '刘德华(Andy Lau)，1961年9月27日出生于中国香港，籍贯广东新会，中国香港影视男演员、歌手、制片人、作词人。1981年出演电影处女作《彩云曲》。1983年主演的武侠剧《神雕侠侣》在香港取得62点的收视纪录。1985年发行首张个人专辑《只知道此刻爱你》。1990年凭借专辑《可不可以》在歌坛获得关注。1991年创办天幕电影公司。1994年获得十大劲歌金曲最受欢迎男歌星奖；同年担任剧情片《天与地》的制片人。1995年在央视春晚上演唱其代表作《忘情水》。2000年凭借警匪片《暗战》获得金像奖最佳男主角奖；同年被《吉尼斯世界纪录大全》评为获奖最多的香港男歌手。2004年凭借剧情片《大块头有大智慧》获得金像奖最佳男主角奖；同年凭借警匪片《无间道3：终极无间》获得金马奖最佳男主角奖 ；同年第六次获得十大劲歌金曲最受欢迎男歌星奖。2005年获得香港UA院线颁发的全港最高累积票房香港男演员奖。2006年获得釜山国际电影节亚洲最有贡献电影人奖。2012年凭借剧情片《桃姐》获得金马奖、金像奖最佳男主角奖；同年担任第49届台湾电影金马奖评审团主席。2015年第5次登上央视春晚并演唱歌曲《回家的路》。2020年发行个人首张数字专辑《演·唱》。演艺事业外，刘德华关心公益慈善。1994年创立刘德华慈善基金会。2000年被评为世界十大杰出青年。2005年发起亚洲新星导计划。2008年被委任为香港非官守太平绅士。2010年获得第12届世界杰出华人奖。2016年连任中国残疾人福利基金会副理事长。'}}, {'keyword': '歌唱家', 'score': 0.578767, 'root': '人物活动-文艺活动', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%AD%8C%E5%94%B1%E5%AE%B6/6461176', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/241f95cad1c8a786d75fe6026409c93d70cf5040', 'description': '歌唱家，即歌唱艺术大家，是指具有精湛的歌唱水平，深厚的艺术水准，高尚的道德修养，并深受广大人民群众爱戴与欢迎的歌者。英文单词Singer 可以翻译为歌唱家，也可以翻译为歌手，两者是一个说法。一个优秀的歌唱家必定拥有给人灵魂震撼，引起人们共鸣，有思想深度的歌曲作品，从而引起人们的印象深刻。树立歌唱者在听众心目中的良好艺术形象和风格形象，用美好的音乐鼓舞人心，感动社会，并且感动世界。'}}, {'keyword': '男孩', 'score': 0.386953, 'root': '人物活动-人物特写', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%94%B7%E5%AD%A9/20490172', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/7dd98d1001e93901213f8c0354a543e736d12f2e38ff', 'description': '《男孩》是由梁博填词、谱曲、编曲并演唱的一首音乐单曲。该音乐单曲由梁博于2017年3月25日在湖南卫视文化娱乐类节目《歌手2017》第10期中首次演唱。'}}, {'keyword': '人脸', 'score': 0.204971, 'root': '人物-人物特写', 'baike_info': {}}, {'keyword': '美女', 'score': 0.01857, 'root': '人物-人物特写', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%BE%8E%E5%A5%B3/109596', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/91529822720e0cf3acdfc0280046f21fbe09aa3d', 'description': '美女，汉语词语，拼音是měi nǚ，意思是容貌姣好、仪态优雅的女子。'}}], 'log_id': 1510963084355863819}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "# 相对路径图片 read bytes 读取二进制格式图片\n",
    "f = open('Liu_01.jpeg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "# 百度百科\n",
    "payload={\n",
    "    'access_token':access_token,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "# params = {\"image\":img}\n",
    "# access_token = access_token\n",
    "# request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data= payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9aa9f599",
   "metadata": {},
   "source": [
    " ## 菜品识别\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "5ca136df",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'calorie': '137', 'has_calorie': True, 'name': '麻婆豆腐', 'probability': '0.970397', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%BA%BB%E5%A9%86%E8%B1%86%E8%85%90/30888', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/a71ea8d3fd1f4134970ab767315582cad1c8a786f0da', 'description': '麻婆豆腐(拼音：má pó dòu fu；英文：sauteed tofu in hot and spicy sauce)，是四川省传统名菜之一，属于川菜，主料为：豆腐，辅料为：蒜苗、牛肉沫(其他肉也可以)，调料为：豆瓣、辣椒面,花椒面、酱油、生抽、老抽、糖、淀粉等，麻来自花椒，辣来自辣椒面，此菜成菜麻、辣、鲜、香、烫、翠、嫩、酥，将川菜麻辣味型的特点展现的淋漓尽致，如今，麻婆豆腐远渡重洋，在美国、加拿大、英国、法国、越南、新加坡、马来西亚、日本、澳大利亚等国安家落户，从一味家常小菜一跃而登上大雅之堂，成了国际名菜。2018年9月10日，“中国菜”正式发布，“麻婆豆腐“被评为“中国菜”四川十大经典名菜。'}}, {'calorie': '192', 'has_calorie': True, 'name': '家常豆腐', 'probability': '0.0103237', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%AE%B6%E5%B8%B8%E8%B1%86%E8%85%90/2254713', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/14ce36d3d539b6007f5531b4e250352ac65cb71d', 'description': '家常豆腐，是一道以豆腐、猪肉作为主要食材，以豆瓣酱、白糖和酱油作为调料制作而成的老少皆宜的美味食品，酸甜苦辣皆宜，味道浓郁。其中含有铁、钙、磷、镁等人体必需的多种微量元素，还含有糖类、植物油和丰富的优质蛋白。动脉硬化、低碘者忌食；肥胖和血脂较高者不宜多食；肝火旺盛者不宜多食；胃肠炎、高血压、肺结核患者慎食。'}}, {'calorie': '82', 'has_calorie': True, 'name': '豆腐饭', 'probability': '0.0079521', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%B1%86%E8%85%90%E9%A5%AD/1590596', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/cdbf6c81800a19d8a33bce0a3dfa828ba61e4680', 'description': '北方一些地方的一种习俗，在年夜饭时一定要有一盘豆腐，取其谐音“都福”，就是都有福气的意思，过年讨个好彩头。有的地方就是一整块的豆腐放在盘子中，再往上浇汤汁就可以了，还有的地方用更复杂的办法做豆腐菜。'}}, {'calorie': '60', 'has_calorie': True, 'name': '蟹粉嫩豆腐', 'probability': '0.00166285', 'baike_info': {}}, {'calorie': '81', 'has_calorie': True, 'name': '豆腐', 'probability': '0.00151747', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%B1%86%E8%85%90/272285', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/78310a55b319ebc43fb525cc8c26cffc1f171691', 'description': '豆腐是一种营养丰富又历史悠久的食材，大众对豆腐的喜爱推动了豆腐制作工艺的前进和发展。豆腐主要的生产过程一是制浆，即将大豆制成豆浆；二是凝固成形，即豆浆在热与凝固剂的共同作用下凝固成含有大量水分的凝胶体，即豆腐。豆腐内含人体必需的多种微量元素，还含有丰富的优质蛋白，素有“植物肉”之美称。豆腐的消化吸收率在95%以上，这样的健康食品一直深受大家的喜爱，但要想更好地发挥豆腐的营养价值，还需要注意做好搭配。2014年，“豆腐传统制作技艺”入选中国第四批国家级非物质文化遗产代表性项目名录，这道神奇的中国美食开始在商品价值之外，被赋予了更多的文化内涵和传承意义。'}}], 'log_id': 1510962897386816268}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/dish\"\n",
    "# 二进制方式打开图片文件\n",
    "# 相对路径图片 read bytes 读取二进制格式图片\n",
    "f = open('mpdf.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "# 百度百科\n",
    "payload={\n",
    "    'access_token':access_token,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "# params = {\"image\":img}\n",
    "# access_token = access_token\n",
    "# request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data= payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "e1991df7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '摇滚乐团', 'score': 0.719986, 'root': '人物活动-文艺活动', 'baike_info': {}}, {'keyword': '猫王', 'score': 0.565429, 'root': '人物-人物特写', 'baike_info': {}}, {'keyword': '婚纱写真', 'score': 0.413316, 'root': '人物-人物特写', 'baike_info': {}}, {'keyword': '屏幕截图', 'score': 0.261572, 'root': '非自然图像-屏幕截图', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE/3634161', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/aa18972bd40735fa016882639c510fb30e240854', 'description': '所谓屏幕截图就是将电脑屏幕上的桌面、窗口、对话框、选项卡等屏幕元素保存为图片。在Windows下用户可以使用键盘上的“打印屏幕系统请求”(Print Screen)按键进行整个屏幕的截图和当前活动窗口的截图(按住Alt键的同时按下Print Screen键)，还可以借助专业的屏幕截图软件进行截图。'}}, {'keyword': '人物特写', 'score': 0.109715, 'root': '人物-人物特写', 'baike_info': {}}], 'log_id': 1510962647980505643}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('12.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':access_token,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "addcda7f",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
